package client.components;

import static client.utils.TBUtils.DEFAULT_DATE_FORMAT;

import java.util.List;

import client.PlanModel;
import client.bean.Plan;
import client.utils.observer.Observable;
import client.utils.observer.Observer;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class PlansTable extends Grid implements Observer {

	public PlansTable() {
		PlanModel.instance.addObserver(this);
		resize(1, PlansTableColumns.values().length);
	}

	@Override
	public void update(Observable o, Object arg) {
		clear();

		addStyleName("plansTable");

		List<Plan> content = PlanModel.instance.getPlans();
		if (content == null) {
			return;
		}

		resize(content.size() + 1, PlansTableColumns.values().length);

		for (PlansTableColumns column : PlansTableColumns.values()) {
			setWidget(0, column.ordinal(), column.getTitleLabel());
		}

		for (int row = 1; row <= content.size(); row++) {
			final Plan plan = content.get(row - 1);
			setWidget(row, 0, new Label("" + row));
			setWidget(row, 1, getPlanNameLink(plan));
			setWidget(row, 2, new Label("" + plan.getMembers().size()));
			setWidget(row, 3, new Label(DEFAULT_DATE_FORMAT.format(plan.getStartTime())));
			setWidget(row, 4, new Label(DEFAULT_DATE_FORMAT.format(plan.getEndTime())));
			setWidget(row, 5, new Button("X"));
		}
	}

	public Widget getPlanNameLink(final Plan plan) {
		Anchor planNameLink = new Anchor(plan.getName());
		planNameLink.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				client.TimeBookController.clearRootPabel();
				client.TimeBookController.displayPlansPanel(plan);
			}
		});
		return planNameLink;
	}

	enum PlansTableColumns {
		ID("No."), NAME("Plan name"), MEMBERS_COUNT("Number of Members"), START_TIME("Start time"), END_TIME("End time"), DELETE("Del");
		private String name;

		PlansTableColumns(String name) {
			this.name = name;
		}

		public Label getTitleLabel() {
			Label header = new Label(name);
			header.addStyleName("planTableHeader");
			return header;
		}
	}
}
